package by.grsu.coctails.fragments;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import by.grsu.coctails.R;
import by.grsu.coctails.adapter.AbstractAdapter;
import by.grsu.coctails.adapter.IngredientAdapter;
import by.grsu.coctails.db.task.CommonGetAsyncTask;
import by.grsu.coctails.db.task.GetIngredientsAsyncTask;
import by.grsu.coctails.model.Ingredient;

public class ListIngredientFragment extends CommonDBFragment<Ingredient> {

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Ingredient ingredient = getAdapter().getList().get(position);
				FragmentCreator
						.addIngredientFragment(getActivity(), ingredient);
			}
		});
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public CommonGetAsyncTask getTask(String categoryName) {
		return new GetIngredientsAsyncTask(getActivity(), categoryName) {

			@Override
			public void onComplete(List<Ingredient> result) {
				success(result);
			}
		};
	}

	public void success(List<Ingredient> result) {
		getAdapter().getList().addAll(result);
		getAdapter().notifyDataSetChanged();
	}

	@Override
	public int getLayoutResource() {
		return R.layout.list_ingredient_fragment;
	}

	@Override
	public AbstractAdapter<Ingredient> createAdapter() {
		List<Ingredient> list = new ArrayList<Ingredient>();
		return new IngredientAdapter(getActivity(), R.layout.ingredient_item,
				list);
	}

	@Override
	public String getTitle() {
		return getString(R.string.all_ingredients);
	}

}
